<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2020/10/26
 * Time: 14:53
 */

namespace app\Service;

use app\api\model\Index\VideoUser;
use app\api\model\Index\VideoUserComment;
use app\api\model\Sns\SnsModel;
use app\api\model\VideoUser\VideoUserLikeModel;
use think\facade\Db;

class VideoService extends BaseService
{

    protected $table;

    public function __construct()
    {
        $this->table = new VideoUser();
    }

    /**
     * 视频发布
     */
    public function save(array $params)
    {

        $validates = $this->validates();
        if (!$validates->check($params)) {
            return $this->messge(0, $validates->getError());
        }
        $date = $this->table->create($params);
        if ($date) {
            return $this->messge(1, 'ok');
        }
        return $this->messge(0, '添加失败');
    }

    /**
     * @param $code
     * @param string $msg
     * @return array|string
     * 返回提示
     */
    public function messge($code, $msg = '')
    {
        $msg = [
            'code' => $code,
            'msg' => $msg,

        ];
        return $msg;
    }

    protected function validates()
    {
        $validate = \think\facade\Validate::rule([
            'title' => 'require|max:25',
            'url' => 'require',
            'user_id' => 'require',
        ]);
        return $validate;
    }

    /**
     * 关注数/点赞数/评论数统计获取
     * 点赞数和评论数  关注状态
     */
    public function likes(int $video_id, $user)
    {
        $user_id = $user ? $user['id'] : 0;
        $info = $this->table->where('id', $video_id)->field('nums_like,nums_forward,nums_discuss,user_id')->find();
        $info['count'] = VideoUserComment::where('video_id', $video_id)->count(); //获取当前视频的评论总条数;
        $info['followed'] = $this->sns_info($user_id, $info['user_id']);
        $info['liked'] = $this->is_likes($video_id, $user_id);
        $info['nums_like'] = $info['nums_like'] > 0 ? $info['nums_like'] : 0; //点赞数
        unset($info['user_id']);
        return $info;
    }

    /**
     * @param $uid 用户ID
     * @param $author_id 作者ID
     */
    protected function sns_info(int $uid, int $author_id): bool
    {
        $sns_info = SnsModel::where(['sns_frommid' => $uid, 'sns_tomid' => $author_id])->find();
        try {
            if ($sns_info) {
                return true;
            } else {
                return false;
            }
        } catch (\Exception $exception) {
            return false;
        }
    }

    /**
     * @param int $video_id 视频ID
     * @param int $user_id 用户ID
     * @return bool
     */
    protected function is_likes(int $video_id, int $user_id): bool
    {
        $likes = VideoUserLikeModel::where(['video_id' => $video_id, 'uid' => $user_id])->field('status')->find();
        try {
            if ($likes && $likes['status'] == 1) {
                return true;
            } else {
                return false;
            }
        } catch (\Exception $exception) {
            return false;
        }
    }

    /**
     * 首页视频列表
     */
    public function video_lists(int $uid, int $limit, int $page, array $where = [], $label = '')
    {
        $offset = ($page - 1) * $limit;
        $result = $this->table
            ->alias('v')
            ->field('v.id,v.url,v.title,v.label,v.img,v.assoc,v.play_num,v.is_show,v.play_default,v.school_id,v.is_recommend,v.address,v.nums_like,v.nums_discuss,v.nums_forward,v.cate_id,v.goods_id,v.course_id,v.user_id,u.id as author_id,u.head_img as author_avatar,u.nickname as author_nickname,v.video_id')
            ->join('hd_user u', 'v.user_id = u.id', 'LEFT')
            ->with(['user', 'video' => function ($query) {
                return $query->field('id,video_title');
            }])
            ->where('v.is_show', 1)
            ->where('v.status', 1)// 正常的视频
            ->when($label, function ($query) use ($label) {
                return $query->where('v.label', 'like', '%' . $label . '%');
            })
            ->limit($offset, $limit)
            ->order('id desc')
            ->where($where)
            ->select()
            ->toArray();
        return $this->FormattingData($result, $uid);
    }

    /**
     * 个人中心视频
     */
    public function user_video_lists(int $uid, int $limit, int $page, array $where = [], $label = '', $user_id)
    {
        $offset = ($page - 1) * $limit;

        if ($user_id == 0) {
            $wheres = [];
        } else {
            $wheres = ['v.is_show' => 1];
        }
        $result = $this->table
            ->alias('v')
            ->field('v.id,v.url,v.title,v.label,v.img,v.assoc,v.play_num,v.is_show,v.play_default,v.school_id,v.is_recommend,v.address,v.nums_like,v.nums_discuss,v.nums_forward,v.cate_id,v.goods_id,v.course_id,v.user_id,u.id as author_id,u.head_img as author_avatar,u.nickname as author_nickname,v.video_id')
            ->join('hd_user u', 'v.user_id = u.id', 'LEFT')
            ->with(['user', 'video' => function ($query) {
                return $query->field('id,video_title');
            }])
            ->where('v.status', 1)// 正常的视频
            ->when($label, function ($query) use ($label) {
                return $query->where('v.label', 'like', '%' . $label . '%');
            })
            ->limit($offset, $limit)
            ->order('id desc')
            ->where($where)
            ->where($wheres)
            ->select()
            ->toArray();
        return $this->FormattingData($result, $uid);
    }

    /**
     * 用户是否关注作者
     * $uid 用户id
     * $author_id 作者ID
     */
    protected function is_followed(int $uid, int $author_id)
    {
        $follow = SnsModel:: field('sns_id,sns_followstate')
            ->where('sns_frommid', $uid)
            ->where('sns_tomid', $author_id)
            ->find();
        try {
            if ($follow) {
                return true;
            } else {
                return false;
            }
        } catch (\Exception $exception) {
            return false;
        }
    }

    /**
     * 数据格式化
     */
    public function FormattingData(array $arr, int $uid)
    {
        $arrs = [];
        foreach ($arr as $item) {
            $item['liked'] = $this->is_likes($item['id'], $uid); //是否点赞
            $item['followed'] = $this->is_followed($uid, $item['user_id']); //是否关注
            $item['be_followed'] = $this->is_followed($item['user_id'], $uid); //是否反关注
            $item['nums_like'] = $item['nums_like'] > 0 ? $item['nums_like'] : 0; //点赞数
            $item['goods_id'] = VideoUser::goodsinfo($item['goods_id']); //关联商品
            $item['course_id'] = VideoUser::courseinfo($item['course_id']); //关联课程
            $arrs[] = $item;

        }
        return $arrs;
    }

    /**
     *  个人中心
     * @param $label 标签
     * @param int $uid 用户Id
     * @param int $type 类型 1 作品 2 动态 3 喜欢
     * @param int $page 分页
     * @param int $limit 每页条数
     */
    public function userCenterList($label, int $uid, int $type, int $page, int $limit, $user_id)
    {
        switch ($type) {
            case 1:
                $where = ['v.user_id' => $uid]; //作品
                break;
            case 2:
                $where = ['v.user_id' => $uid]; //动态
                break;
            case 3:
                $where['v.id'] = array('in', $this->userLike($uid)); //喜欢
                break;
        }
        return $this->user_video_lists($uid, $limit, $page, $where, $label, $user_id); //喜欢;
    }

    /**
     * 喜欢的作品
     */
    public function userLike(int $uid): string
    {
        if ($ids = VideoUserLikeModel::where('uid', $uid)->column('video_id')) {
            return implode(',', $ids);
        }
        return '';
    }

    /**
     * 视频上架/下架操作
     */
    public function video_is_show_lists(int $user_id, int $video_id, int $is_show)
    {
        $res = $this->table->find($video_id);
        if (!$res) return false;
        $res->is_show = $is_show;
        if ($res->save()) {
            return true;
        }
        return false;
    }
}